﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlServerCe;
using System.Configuration;
using System.Data;

namespace xFeedApp.DAL
{
    public class DBConnection
    {
        static SqlCeConnection scon = new SqlCeConnection(ConfigurationManager.ConnectionStrings["xFeedApp.Properties.Settings.ConfigDBConnectionString"].ConnectionString);
        SqlCeDataAdapter sda;

        public DBConnection()
        {
            sda = new SqlCeDataAdapter();
        }

        public void BindDataGrid(ref System.Windows.Forms.DataGridView dgv, string Tbl)
        {
            BindDataGrid(ref dgv, "", Tbl, "");
        }

        public void BindDataGrid(ref System.Windows.Forms.DataGridView dgv, string Cols, string Tbl, string Where)
        {
            sda = new SqlCeDataAdapter();
            SqlCeCommandBuilder scb = new SqlCeCommandBuilder();
            sda.SelectCommand = new SqlCeCommand("SELECT " + (!string.IsNullOrEmpty(Cols) ? Cols : "*") + " FROM " + Tbl + (!string.IsNullOrEmpty(Where) ? " WHERE " + Where : ""),scon);
            scb.DataAdapter = sda;
            scb.SetAllValues = true;
            sda.DeleteCommand = scb.GetDeleteCommand();
            sda.InsertCommand =  scb.GetInsertCommand();
             sda.UpdateCommand = scb.GetUpdateCommand();
            DataTable tbl = new DataTable();
            sda.FillSchema(tbl,SchemaType.Source);
            sda.Fill(tbl);
            dgv.DataSource = tbl;
            dgv.Refresh();
        }

        public void SaveData(DataTable tbl)
        {
            if (sda == null)
                throw new System.Exception("Problem with saving process! Data haven't been defined!");
            
            sda.Update(tbl);
        }
    }
}
